package com.erp.freight.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.erp.freight.domain.fpx.*;
import com.erp.freight.domain.param.OrderParam;
import com.ruoyi.order.api.domain.OrderStatusParam;
import com.erp.freight.service.IFpxLogisticsService;
import com.erp.freight.service.KjxLogisticsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fpx.api.constants.AmbientEnum;
import com.fpx.api.model.AffterentParam;
import com.fpx.api.utils.ApiHttpClientUtils;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.common.core.utils.Threads;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductSku;
import com.ruoyi.gather.api.domain.QueryProductParam;
import com.ruoyi.order.api.RemoteErpChildOrderService;
import com.ruoyi.order.api.RemoteErpOrderLogService;
import com.ruoyi.order.api.RemoteErpOrderService;
import com.ruoyi.order.api.domain.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RestController
@RequestMapping("/purchase/fpx")
@Slf4j
public class FpxLogistics {
    // public static String FPS_APP_KEY = "81de1c6f-d840-4ede-a42b-a99154566509";
    // //测试
    public static String FPS_APP_KEY = "d8ccd4bb-0a39-4cd1-87c2-f5cce0fb323d";
    // public static String FPS_APP_SECRET =
    // "dd5edf06-81a4-4392-845b-9251f827f07f";// 测试
    public static String FPS_APP_SECRET = "f3166d57-ce09-4cff-9b6f-8c96734945a7";
    private final IFpxLogisticsService ifpxLogisticsService;
    private final KjxLogisticsService kjxLogisticsService;
    private final RemoteErpChildOrderService remoteErpChildOrderService;
    private final RemoteErpOrderLogService remoteErpOrderLogService;
    private final RemoteErpOrderService remoteErpOrderService;

    /**
     * 出库
     */
    @PostMapping("/sendOutOrderToFPX")
    public R<String> sendOutOrderToFPX(@RequestBody OrderParam orderParam) throws JsonProcessingException {
        Long orderId = orderParam.getOrderId();
        List<ErpSellerChildOrderExtend> childOrderExtends = remoteErpChildOrderService.getChildExtendByOrder(orderId);
        ErpSellerChildOrderExtend childExtend = childOrderExtends.get(0);
        String consignmentNo = null;
        if (childExtend.getType() == 3) {
            try {
                consignmentNo = kjxLogisticsService.submitOrderAndPack(orderId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (childExtend.getType() == 1) {
            consignmentNo = ifpxLogisticsService.createOrderFPX(orderId);
        }
        if (StringUtils.isNotEmpty(consignmentNo)) {
            for (ErpSellerChildOrderExtend childOrderExtend : childOrderExtends) {
                childOrderExtend.setConsignmentNo(consignmentNo);
                remoteErpChildOrderService.updateChildExtend(childOrderExtend);
            }
            // 日志
            remoteErpOrderLogService.createOrderLog(orderId, null, OrderLogType.CreateOutWarehouseGoods,
                    null, OrderProcessFlag.CaiNiao.getInfo(), "106");
            remoteErpOrderService.setInnerStatus(orderId, "106", OrderProcessFlag.CaiNiao.getInfo());
        }

        return R.ok("发货成功");
    }

    /**
     * 判断商品是否全部入库
     */
    @GetMapping("/isInBound")
    public R<Object> isInBound(Long orderId) {
        // 仓储发货跳过判断
//        ErpSellerOrderExtend orderExtend = orderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId));
//        if (orderExtend != null && orderExtend.getIsWarehouse() == 2) {
//            return R.ok(true);
//        }
//        List<ErpSellerChildOrder> childOrderList = sellerChildOrderService.getChildOrderByOrderId(orderId);
////        ErpSendOutGoods sendOutGoods = sendOutGoodsService.getSendGoodsByChildOrderId(childOrderList.get(0).getChildOrderId());
//        List<ErpSellerChildOrderExtend> childOrderExtendList = erpSellerChildOrderExtendMapper.selectList(new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getOrderId, orderId));
//        ErpSellerChildOrderExtend sendOutGoods = childOrderExtendList.get(0);
//        Integer type = sendOutGoods.getType();
//        if (type != 1) {
//            return R.ok(true);
//        }
//        int inBoundCount = 0; // 入库数量
//        for (ErpSellerChildOrder childOrder : childOrderList) {
//            String childOrderId = childOrder.getChildOrderId();
//            AffterentParam publicParam = new AffterentParam();
//            publicParam.setAppKey(FPS_APP_KEY);
//            publicParam.setAppSecret(FPS_APP_SECRET);
//            publicParam.setFormat("json");
//            publicParam.setVersion("1.0.0");
//            publicParam.setLanguage("CN");
//            publicParam.setMethod("fu.wms.inbound.getlist");
//            HashMap<String, Object> map = new HashMap<>();
//            Long endTime = System.currentTimeMillis();
//            Long startTime = getPastDate(7);
//            map.put("ref_no", childOrderId);
//            map.put("create_time_start", startTime);
//            map.put("create_time_end", endTime);
//            String inBoundResult = ApiHttpClientUtils.apiJsongPost(publicParam, map, AmbientEnum.FORMAT_ADDRESS);
//            JSONObject inBoundResultJson = JSONObject.parseObject(inBoundResult);
//            JSONArray inBoundData = inBoundResultJson.getJSONObject("data").getJSONArray("data");
//            if (ObjectUtils.isEmpty(inBoundData)) {
//                return R.fail(false,"订单商品未全部入库");
//            } else {
//                JSONObject o = inBoundData.getJSONObject(0);
//                String status = o.getString("status");
//                if ("C".equals(status)) { // 表示已上架
//                    inBoundCount++;
//                }
//            }
//        }
//        if (inBoundCount != 0 && inBoundCount == childOrderList.size()) {
//            if (orderExtend != null) {
//                orderExtend.setIsWarehouse(1);
//                orderExtendMapper.updateById(orderExtend);
//            } else {
//                orderExtend = new ErpSellerOrderExtend();
//                orderExtend.setOrderId(orderId);
//                orderExtend.setIsWarehouse(1);
//                orderExtendMapper.insert(orderExtend);
//            }
//            return R.ok(true);
//        }
//        return R.fail(false,"订单商品未全部入库");
        return R.ok(true);
    }

//    /**
//     * TODO 查询海关编码
//     */
//    @GetMapping("/getHsCodeList")
//    public R<Object> getHsCodeList(ErpCollectProductHsBo bo) {
//        List<ErpCollectProductHsVo> queryList = collectProductHsService.queryList(bo);
//        List<Map<String, Object>> list = new ArrayList<>();
//        queryList.forEach(vo -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("label", vo.getCiqName());
//            map.put("value", vo.getId());
//            list.add(map);
//        });
//        return R.ok(list);
//    }

    /**
     * 同步国内运单号 变为已采购
     */
    @PostMapping("/purchased")
    @RepeatSubmit
    public R<String> purchased(@RequestBody ErpSendOutGoods orderParam) {
        String childOrderId = orderParam.getChildOrderId();
        String trackingNo = orderParam.getTrackingNo();
        Long arrivalTime = orderParam.getArrivalTime();
        String kjxProductName = orderParam.getKjxProductName();
        Integer type = orderParam.getType();
        // 根据子订单查出订单
        ErpSellerChildOrder erpSellerChildOrder = remoteErpChildOrderService.getChildByChildId(childOrderId);
        Long orderId = erpSellerChildOrder.getOrderId();
        String skuCode = erpSellerChildOrder.getSkuCode();
        
        // 保存快递信息
        ErpSellerChildOrderExtend childOrderExtend = remoteErpChildOrderService.getChildExtendByChildOrder(childOrderId);
        if (childOrderExtend == null) {
            childOrderExtend = new ErpSellerChildOrderExtend();
            childOrderExtend.setOrderId(orderId);
            childOrderExtend.setChildOrderId(Long.parseLong(childOrderId));
            childOrderExtend.setType(type);
        } else {
            if (type == 1) {
                // 判断运单号是否已填,填了说明入库了,需要先取消入库
                String inBound = getInBound(childOrderId);
                JSONObject inBoundJsonObject = JSONObject.parseObject(inBound);
                JSONArray inBoundData = inBoundJsonObject.getJSONObject("data").getJSONArray("data");
                // 已经创建了入库
                if (ObjectUtils.isNotEmpty(inBoundData)) {
                    R<String> returnCancel = cancelInBound(childOrderId);
                    if (returnCancel.getCode() != 200) {
                        return returnCancel;
                    }
                    Threads.sleep(3000); //取消太快重新创建会失败
                }
            }
        }

        //当走4px时，才发货
        String inConsignNo = null;
        if (type == 1) {
            Long productCount = erpSellerChildOrder.getProductCount();
            R<String> inBoundJsonObject = createInBound(childOrderId, trackingNo, arrivalTime, productCount.intValue(), skuCode);
            if (inBoundJsonObject.getCode() != 200)
                return inBoundJsonObject;
            // 获取入库委托单号
            String data = inBoundJsonObject.getMsg();
            JSONObject jsonObject = JSONObject.parseObject(data);
            inConsignNo = jsonObject.getJSONObject("data").getString("consignment_no");
        }
        // 日志记录
        String OrderProcess = null;
        if (type == 2) {
            OrderProcess = "offline";
        } else {
            OrderProcess = "cainiao";
        }
        if (childOrderExtend.getCnTrackingNo() == null) { // 添加
            remoteErpOrderLogService.createOrderLog(orderId, childOrderId, OrderLogType.FillInTracking, trackingNo,
                    OrderProcess, "103");
        } else if (childOrderExtend.getCnTrackingNo() != null && !trackingNo.equals(childOrderExtend.getCnTrackingNo())) { // 修改
            remoteErpOrderLogService.createOrderLog(orderId, childOrderId, OrderLogType.ModifyInTracking, trackingNo,
                    OrderProcess, "103");
        }

        childOrderExtend.setCnTrackingNo(trackingNo);
        childOrderExtend.setArrivalTime(arrivalTime);
        childOrderExtend.setType(type);
        childOrderExtend.setKjxProductName(kjxProductName);
        remoteErpChildOrderService.updateChildExtend(childOrderExtend);

        // 判断该订单的子订单是否全部填写国内运单号
        List<ErpSellerChildOrderExtend> childOrderExtendList = remoteErpChildOrderService.getChildExtendByOrder(orderId);
        List<ErpSellerChildOrderExtend> collect = childOrderExtendList.stream()
                .filter(str -> str.getCnTrackingNo() != null && str.getProof() != null).collect(Collectors.toList());
        // 根据订单获取子订单
        List<ErpSellerChildOrder> childOrderList = remoteErpChildOrderService.getChildByOrder(orderId);
        if (collect.size() == childOrderList.size()) {
//            ErpSellerOrderLog statusIntro = remoteErpOrderLogService.getStatusIntro(orderId);
            if (type != 2) {
                //走4px入库，变为已采购
//                statusIntro.setCurrentStatus("105");
//                statusIntro.setOrderProcessFlag("cainiao");
//                orderLogService.updateByBo(BeanUtil.toBean(statusIntro, ErpSellerOrderLogBo.class));
                remoteErpOrderService.setInnerStatus(orderId, "105", OrderProcessFlag.CaiNiao.getInfo());
            } else {
                //不走4px入库，变为声明发货
//                statusIntro.setCurrentStatus("108");
//                statusIntro.setOrderProcessFlag("offline");
//                orderLogService.updateByBo(BeanUtil.toBean(statusIntro, ErpSellerOrderLogBo.class));
                remoteErpOrderService.setInnerStatus(orderId, "108", OrderProcessFlag.Offline.getInfo());
            }
        }

        return R.ok();

    }

    /**
     * 入库
     *
     * @param refNo        委托参考号
     * @param trackingNo   国内运单号
     * @param arrivalTime  预计到货时间
     * @param productCount 数量
     * @param skuCode      商品
     * @return null为成功
     */
    private static R<String> createInBound(String refNo, String trackingNo, Long arrivalTime, Integer productCount, String skuCode) {
        JsonMapper jsonMapper = new JsonMapper();
        // 创建入库委托
        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");

        CreateInBound createInBound = new CreateInBound();
        createInBound.setRef_no(refNo);
        createInBound.setIs_pickup("N");
        createInBound.setFrom_warehouse_code("CNDGMB");
        createInBound.setTo_warehouse_code("CNDGMB");
        createInBound.setDistribution_point("CNDGMB");
        createInBound.setTransport_type("E");
        createInBound.setTracking_no(trackingNo);
        Supplier_address supplier_address = new Supplier_address();
        supplier_address.setCountry("CN");
        supplier_address.setState("广东省");
        supplier_address.setCity("东莞市");
        supplier_address.setDistrict("沙田镇");
        supplier_address.setStreet("穗丰年进港南路第一产业园2号仓13号门");
        supplier_address.setPlan_arrive_time(arrivalTime);
        createInBound.setSupplier_address(supplier_address);
        createInBound.setOcustoms_service("D1");
        createInBound.setIcustoms_service("D3");
        createInBound.setPrint_box_no("Y");
        createInBound.setPrint_box_type("Z");
        List<ConsignmentSku> iconsignmentSkus = new ArrayList<>();
        ConsignmentSku iconsignmentSku = new ConsignmentSku();
        iconsignmentSku.setBox_no("1");
        iconsignmentSku.setBox_barcode(trackingNo);
        iconsignmentSku.setSku_code(skuCode);
        iconsignmentSku.setPlan_qty(productCount);
        iconsignmentSkus.add(iconsignmentSku);
        createInBound.setIconsignment_sku(iconsignmentSkus);
        publicParam.setMethod("fu.wms.inbound.create");
        publicParam.setVersion("1.1.0");
        JSONObject createInBoundJson = null;
        try {
            createInBoundJson = JSONObject.parseObject(jsonMapper.writeValueAsString(createInBound));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String createInBoundReturn = ApiHttpClientUtils.apiJsongPost(publicParam, createInBoundJson,
                AmbientEnum.FORMAT_ADDRESS);
        JSONObject inBoundJsonObject = JSONObject.parseObject(createInBoundReturn);
        if ("0".equals(inBoundJsonObject.getString("result"))) {
            return R.fail(inBoundJsonObject.getJSONArray("errors").getJSONObject(0).getString("error_msg"));
        }
        return R.ok(createInBoundReturn);
    }

    /**
     * 提交待发货审核订单
     */
    @GetMapping("/autoSubmitForReview")
    @RepeatSubmit
    public R<Object> autoSubmitForReview() {
        return ifpxLogisticsService.autoSubmitForReview();
    }


    @PostMapping("/submitForReview")
    @RepeatSubmit
    public R<Object> submitForReview(@RequestBody OrderStatusParam param) {
        return ifpxLogisticsService.submitForReview(param);
    }


    /**
     * TODO 4px 仓储
     */
/*    @PostMapping("/sendOutGoodsToFPX")
    public R<String> sendOutGoodsToFPX(@RequestBody OrderParam orderParam) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        List<ConsignmentSku> iconsignmentSkus = new ArrayList<>();
        ConsignmentSku iconsignmentSku = new ConsignmentSku();
        String trackingNo = orderParam.getTrackingNo();
        Long arrivalTime = orderParam.getArrivalTime();
        String skuCode = orderParam.getSkuCode();
        Integer productCount = orderParam.getProductCount();
        ErpCollectProductSku skuInfo = collectProductSkuMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        if (skuInfo == null) {
            return R.fail("找不到商品，请输入正确的商品编码");
        }
        Long collectProductId = skuInfo.getCollectProductId();
        ErpCollectProduct collectProduct = collectProductMapper
                .selectOne(new LambdaQueryWrapper<ErpCollectProduct>().eq(ErpCollectProduct::getId, collectProductId));

        // 还是得判断sku是否在4px已创建
        String createSkuReturn = iFpxLogisticsService.createSku(skuCode, "CNY", skuInfo.getSkuPrice());
        if (createSkuReturn != null) {
            JSONObject skuJsonObject = JSONObject.parseObject(createSkuReturn);
            if ("0".equals(skuJsonObject.getString("result"))) {
                throw new RuntimeException(skuJsonObject.getJSONArray("errors").toString());
            }
        }
        iconsignmentSku.setSku_code(skuCode);
        iconsignmentSku.setPlan_qty(productCount);
        iconsignmentSku.setSku_name(collectProduct.getSubject());
        iconsignmentSkus.add(iconsignmentSku);
        // 仓储的委托参考号随机生成
        Long time = new Date().getTime();
        R<String> inBound = createInBound(time.toString(), trackingNo, arrivalTime, productCount, skuCode);
        if (inBound.getCode() != 200) {
            return inBound;
        }
        String data = inBound.getMsg();
        JSONObject inBoundJsonObject = JSONObject.parseObject(data);
        // 入库委托成功,记录
//         入库委托单号,用来查询入库状态
        String consignmentNo = inBoundJsonObject.getJSONObject("data").getString("consignment_no");
        FpxWarehousInfo fpxWarehousInfo = new FpxWarehousInfo();
        FpxWarehousRecord fpxWarehousRecord = new FpxWarehousRecord();
        for (ConsignmentSku skus : iconsignmentSkus) {
            // 修改仓储信息表
            FpxWarehousInfo warehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                    .eq(FpxWarehousInfo::getUserId, 1L).eq(FpxWarehousInfo::getSkuCode, skus.getSku_code()));
            if (warehousInfo == null) { // 初始化
                fpxWarehousInfo.setSkuCode(skus.getSku_code());
                fpxWarehousInfo.setOnwayStock(skus.getPlan_qty());
                fpxWarehousInfo.setSkuName(collectProduct.getSubject());
                fpxWarehousInfo.setSkuImage(skuInfo.getSkuImage());
                fpxWarehousInfo.setAvailableStock(0);
                fpxWarehousInfo.setPendingStock(0);
                fpxWarehousInfo.setUserId(1L); // 都是给公司仓储
                warehousInfoMapper.insert(fpxWarehousInfo);
            } else {
                warehousInfo.setOnwayStock(warehousInfo.getOnwayStock() + skus.getPlan_qty());
                warehousInfoMapper.updateById(warehousInfo);
            }
            // 在仓储记录表新增
            fpxWarehousRecord.setUserId(1L);
            fpxWarehousRecord.setRefNo(trackingNo);
            fpxWarehousRecord.setConsignmentNo(consignmentNo);
            fpxWarehousRecord.setSkuCode(skus.getSku_code());
            fpxWarehousRecord.setSkuPlanQty(skus.getPlan_qty());
            fpxWarehousRecord.setSkuReceivedQty(0);
            fpxWarehousRecord.setStatus(0);
            fpxWarehousRecord.setProof(orderParam.getProof());
            fpxWarehousRecord.setPurchasePrice(orderParam.getPurchasePrice());
            warehousRecordMapper.insert(fpxWarehousRecord);
        }
        return R.ok("仓储申请创建成功");
    }*/



    /**
     * 判断库存是否足够,并将订单变为仓储发货订单
     */
    @GetMapping("/determineInventory")
    public R<String> determineInventory(Long orderId) {

        /*List<ErpSellerChildOrder> erpSellerChildOrderList = sellerChildOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId));
        for (ErpSellerChildOrder erpSellerChildOrder : erpSellerChildOrderList) {
            String skuCode = erpSellerChildOrder.getSkuCode();
            FpxWarehousInfo fpxWarehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                    .eq(FpxWarehousInfo::getSkuCode, skuCode));
            if (fpxWarehousInfo == null) {
                return R.fail(erpSellerChildOrder.getSkuCode() + "没有库存信息");
            }
            Integer availableStock = fpxWarehousInfo.getAvailableStock();
            int prodQty = erpSellerChildOrder.getProductCount().intValue();
            // 判断用户库存量
            if (availableStock < prodQty) {
                return R.fail(erpSellerChildOrder.getSkuCode() + "库存量不足");
            }
        }

        // 将拓展表改为已入库
        ErpSellerOrderExtend orderExtend = orderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrderExtend>()
                .eq(ErpSellerOrderExtend::getOrderId, orderId));
        if (orderExtend == null) {
            orderExtend = new ErpSellerOrderExtend();
            orderExtend.setOrderId(orderId);
            orderExtendMapper.insert(orderExtend);
        }
        orderExtend.setIsWarehouse(2);
        orderExtendMapper.updateById(orderExtend);

        // 库存充足减库存
        FpxWarehousRecord fpxWarehousRecord = new FpxWarehousRecord();
        for (ErpSellerChildOrder childOrder : erpSellerChildOrderList) {
            String skuCode = childOrder.getSkuCode();
            Long productCount = childOrder.getProductCount();
            String childOrderId = childOrder.getChildOrderId();
            FpxWarehousInfo fpxWarehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                    .eq(FpxWarehousInfo::getSkuCode, skuCode));
            fpxWarehousInfo.setPendingStock((int) (fpxWarehousInfo.getPendingStock() + productCount));
            fpxWarehousInfo.setAvailableStock((int) (fpxWarehousInfo.getAvailableStock() - productCount));
            warehousInfoMapper.updateById(fpxWarehousInfo);
            // 添加记录
            fpxWarehousRecord.setUserId(1L);
            fpxWarehousRecord.setStatus(2);
            fpxWarehousRecord.setRefNo(orderId.toString());
            fpxWarehousRecord.setSkuPlanQty(childOrder.getProductCount().intValue());
            fpxWarehousRecord.setSkuReceivedQty(0);
            fpxWarehousRecord.setSkuCode(skuCode);
            warehousRecordMapper.insert(fpxWarehousRecord);

            ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
                    .eq(ErpSellerChildOrderExtend::getChildOrderId, childOrderId));
            if (childOrderExtend == null) {
                childOrderExtend = new ErpSellerChildOrderExtend();
                childOrderExtend.setOrderId(orderId);
                childOrderExtend.setChildOrderId(Long.parseLong(childOrderId));
                erpSellerChildOrderExtendMapper.insert(childOrderExtend);
            }
            // 获取到最新一条的入库完成记录
            List<FpxWarehousRecord> recordList = warehousRecordMapper.selectList(new LambdaQueryWrapper<FpxWarehousRecord>()
                    .eq(FpxWarehousRecord::getSkuCode, skuCode)
                    .eq(FpxWarehousRecord::getStatus, 1)
                    .orderByDesc(BaseEntity::getCreateTime));
            if (!recordList.isEmpty()) {
                // 采购价和凭证
                FpxWarehousRecord record = recordList.get(0);
                String purchasePrice = record.getPurchasePrice();
                Integer skuPlanQty = record.getSkuPlanQty();
                String proof = record.getProof();
                if (StringUtils.isNotEmpty(purchasePrice)) {
                    BigDecimal skuPurchase = new BigDecimal(purchasePrice).divide(new BigDecimal(skuPlanQty))
                            .multiply(new BigDecimal(productCount)).setScale(2, RoundingMode.HALF_EVEN);
                    childOrderExtend.setPurchasePrice(skuPurchase.doubleValue());
                    childOrderExtend.setProof(proof);
                    // 发货方式改为4px
                    childOrderExtend.setType(1);
                    erpSellerChildOrderExtendMapper.updateById(childOrderExtend);
                    fpxWarehousRecord.setPurchasePrice(purchasePrice);
                    fpxWarehousRecord.setProof(proof);
                    warehousRecordMapper.updateById(fpxWarehousRecord);
                    // 发货方式改为4px
                }
            }
        }

        // 改变订单状态为已采购,等待发货
        orderLogService.createOrderLog(orderId, null, OrderLogType.HasBeenPurchase,
                "", OrderProcessFlag.CaiNiao.getInfo(), "105");
        sellerOrderService.setInnerStatus(orderId, "105", "cainiao");*/

        return R.ok();
    }

    /**
     * 仓储发货
     */
    @PostMapping("/warehousGoodsOutFPX")
    public R<String> warehousGoodsOutFPX(@RequestBody OrderParam orderParam) throws JsonProcessingException {
        /*AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        publicParam.setMethod("fu.wms.outbound.create");
        JsonMapper jsonMapper = new JsonMapper();
        Long orderId = orderParam.getOrderId();
        Oconsignment_sku oconsignment_sku = new Oconsignment_sku();
        List<Oconsignment_sku> oconsignmentSkuses = new ArrayList<>();
        List<ErpSellerChildOrder> erpSellerChildOrderList = sellerChildOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId));
        for (ErpSellerChildOrder erpSellerChildOrder : erpSellerChildOrderList) {

            String skuCode = erpSellerChildOrder.getSkuCode();

            FpxWarehousInfo fpxWarehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                    .eq(FpxWarehousInfo::getSkuCode, skuCode));
            if (fpxWarehousInfo == null) {
                return R.fail(erpSellerChildOrder.getSkuCode() + "没有库存信息");
            }
            Integer availableStock = fpxWarehousInfo.getAvailableStock();
            int prodQty = erpSellerChildOrder.getProductCount().intValue();
            // 判断用户库存量
            if (availableStock < prodQty) {
                return R.fail(erpSellerChildOrder.getSkuCode() + "库存量不足");
            }
            oconsignment_sku.setStock_quality("S");
            oconsignment_sku.setQty(prodQty);
            oconsignment_sku.setSku_code(skuCode);
            oconsignmentSkuses.add(oconsignment_sku);
            oconsignment_sku = new Oconsignment_sku();
        }
        CreateOutBound createOutBound = new CreateOutBound();
        createOutBound.setRef_no(orderId.toString());
        createOutBound.setFrom_warehouse_code("CNDGMB");
        createOutBound.setConsignment_type("S");
        Logistics_service_info logistics_serviceInfo = new Logistics_service_info();
        logistics_serviceInfo.setLogistics_product_code("B068");
        logistics_serviceInfo.setPrint_delivery("N");
        createOutBound.setLogistics_service_info(logistics_serviceInfo);
        AeStoreOrderReceiptAddress address = storeOrderReceiptAddressMapper
                .selectOne(new LambdaQueryWrapper<AeStoreOrderReceiptAddress>()
                        .eq(AeStoreOrderReceiptAddress::getOrderId, orderId));
        Supplier_address supplier_address = new Supplier_address();
        supplier_address.setCountry(address.getPhoneCountry());
        supplier_address.setState(address.getProvince());
        String country = address.getCountry();
        if (country.equals("UK")) {
            country = "GB";
        }
        supplier_address.setCountry(country);
        supplier_address.setPost_code(address.getZip());
        supplier_address.setStreet(address.getDetailAddress());
        supplier_address.setFirst_name(address.getContactPerson());

        createOutBound.setOconsignment_desc(supplier_address);
        createOutBound.setOconsignment_sku(oconsignmentSkuses);
        JSONObject outBoundJson = JSONObject.parseObject(jsonMapper.writeValueAsString(createOutBound));
        String s1 = ApiHttpClientUtils.apiJsongPost(publicParam, outBoundJson, AmbientEnum.FORMAT_ADDRESS);
        JSONObject jsonObject = JSONObject.parseObject(s1);
        String consignment_no = jsonObject.getString("consignment_no");
        FpxWarehousRecord fpxWarehousRecord = new FpxWarehousRecord();
        if ("1".equals(jsonObject.getString("result"))) { // 创建出库委托成功
            sellerOrderService.setInnerStatus(orderId, "106", OrderProcessFlag.CaiNiao.getInfo()); // 待同步国际运单
            // 减可用库存,增待出库存
            for (Oconsignment_sku oconsignmentSku : oconsignmentSkuses) {
                Integer qty = oconsignmentSku.getQty();
                String sku_code = oconsignmentSku.getSku_code();
                FpxWarehousInfo warehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                        .eq(FpxWarehousInfo::getSkuCode, sku_code));
                warehousInfo.setOnwayStock(warehousInfo.getOnwayStock() - qty);
                warehousInfo.setPendingStock(warehousInfo.getPendingStock() + qty);
                warehousInfoMapper.updateById(warehousInfo);

                // 记录
                fpxWarehousRecord.setUserId(1L);
                fpxWarehousRecord.setStatus(2);
                fpxWarehousRecord.setConsignmentNo(consignment_no);
                fpxWarehousRecord.setRefNo(orderId.toString());
                fpxWarehousRecord.setSkuPlanQty(qty);
                fpxWarehousRecord.setSkuReceivedQty(0);
                warehousRecordMapper.insert(fpxWarehousRecord);
            }
        }*/

        return R.ok("发货成功,待同步国际运单");
    }

    /**
     * 商品列表并展示库存
     */
    @GetMapping("/getUserProduct")
    public TableDataInfo<ErpSellerStoreProductSku> getUserProduct(QueryProductParam param, PageQuery pageQuery) {
//        TableDataInfo<ErpSellerStoreProductSku> skuAndProduct = sellerStoreProductSkuService.getSkuAndProduct(pageQuery,
//                param);
//        Long userId = param.getUserId();
//        List<ErpSellerStoreProductSku> rows = skuAndProduct.getRows();
//        for (ErpSellerStoreProductSku row : rows) {
//            String skuCode = row.getSkuCode();
//            FpxWarehousInfo warehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
//                    .eq(FpxWarehousInfo::getSkuCode, skuCode).eq(FpxWarehousInfo::getUserId, userId));
//            row.setFpxWarehousInfo(warehousInfo);
//        }
//        return skuAndProduct;
        return new TableDataInfo<>();
    }

    /**
     * 查看仓储信息
     *
     * @return
     */
/*    @GetMapping("/getWarehousInfo")
    public TableDataInfo<FpxWarehousInfoVo> getWarehousInfo(FpxWarehousInfoBo bo, PageQuery page) {
//        Long userId = LoginHelper.getUserId();
//        bo.setUserId(userId);
        return warehousInfoService.queryPageList(bo, page);
    }*/

    /**
     * 查看仓储流水
     */
/*    @GetMapping("/getWarehousRecords")
    public TableDataInfo<FpxWarehousRecordVo> getWarehousRecords(FpxWarehousRecordBo bo, PageQuery page) {
        return warehousRecordService.queryPageList(bo, page);
    }*/

    /**
     * 费用试算
     */
    @GetMapping("/getPriceCalculator")
    public R<Map<String, Double>> priceCalculator(String weight, String width, String length, String height,
                                                  String country) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        publicParam.setMethod("ds.xms.estimated_cost.get");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("weight", weight);
        paramMap.put("width", width);
        paramMap.put("length", length);
        paramMap.put("height", height);
        paramMap.put("country_code", country);
        String s = ApiHttpClientUtils.apiJsongPost(publicParam, paramMap, AmbientEnum.FORMAT_ADDRESS);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray data = jsonObject.getJSONArray("data");
        List<Double> amount = new ArrayList<>();
        for (Object datum : data) {
            JSONObject d = (JSONObject) datum;
            Double lump_sum_fee = d.getDouble("lump_sum_fee");
            amount.add(lump_sum_fee);
        }
        Collections.sort(amount);
        Map<String, Double> map = new HashMap<>();
        Double lumpSumFee = 0d;
        if (amount.size() > 1)
            lumpSumFee = amount.get(1);
        else
            lumpSumFee = amount.get(0);
        map.put("amount", lumpSumFee);
        return R.ok(map);
    }


    @GetMapping("/getNewPriceCalculator")
    public R<Map<String, Double>> newPriceCalculator(String weight, String width, String length, String height, String country) {
//        Map<String, Object> aeMap = new HashMap();
//        aeMap.put("length", length);
//        aeMap.put("width", width);
//        aeMap.put("height", height);
//        aeMap.put("weight", weight);
//        aeMap.put("country", country);
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/getNewPriceCalculator", aeMap, String.class);
//        String body = (String) forEntity.getBody();


        Map<String, Double> map = new HashMap();
        map.put("amount", 0D);
        return R.ok(map);
    }

    public String cancelOutBound(Long orderId) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setVersion("1.0.0");
        publicParam.setMethod("fu.wms.outbound.cancel");
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setLanguage("CN");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("ref_no", orderId.toString());
        paramMap.put("cancel_type", "BC");
        return ApiHttpClientUtils.apiJsongPost(publicParam, paramMap, AmbientEnum.FORMAT_ADDRESS);
    }

    /**
     * 入库委托查询
     */
    @GetMapping("/getInBound")
    public String getInBound(String refNo) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setVersion("1.0.0");
        publicParam.setMethod("fu.wms.inbound.getlist");
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setLanguage("CN");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("ref_no", refNo);
        paramMap.put("warehouse_code", "CNDGMB");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 7);
        Long startTime = calendar.getTime().getTime();
        paramMap.put("create_time_start", startTime);
        paramMap.put("create_time_end", new Date().getTime());
        return ApiHttpClientUtils.apiJsongPost(publicParam, paramMap, AmbientEnum.FORMAT_ADDRESS);
    }

    /**
     * 查询出库委托
     */
    public String getOutBound(String orderId) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setVersion("1.0.0");
        publicParam.setLanguage("CN");
        publicParam.setMethod("fu.wms.outbound.getlist");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("ref_no", orderId);
        return ApiHttpClientUtils.apiJsongPost(publicParam, paramMap, AmbientEnum.FORMAT_ADDRESS);
    }

    /**
     * 截单成功,根据条件判断是否仓储
     */
/*    @PostMapping("/cutOrderSuccess")
    public R<Object> cutOrderSuccess(@RequestBody OrderParam orderParam) {
        Long orderId = orderParam.getOrderId();
        List<ErpSellerChildOrder> childOrderList = sellerChildOrderService.getChildOrderByOrderId(orderId);
        ErpSellerOrder sellerOrder = sellerOrderMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
        String sellerLoginId = sellerOrder.getSellerLoginId();
        ErpSellerStoreEmpower storeEmpower = sellerStoreEmpowerMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerStoreEmpower>().eq(ErpSellerStoreEmpower::getStoreUserName,
                        sellerLoginId));
        Long userId = storeEmpower.getUserId();
        String statusIntro = "";
        // 订单填写了凭证或国内运单号,转为仓储;都没填退款
        List<ErpSendOutGoods> sendOutGoodList = erpSendOutGoodsMapper
                .selectList(new LambdaQueryWrapper<ErpSendOutGoods>().eq(ErpSendOutGoods::getOrderId, orderId)
                        .eq(ErpSendOutGoods::getIsUse, 1).isNull(ErpSendOutGoods::getTrackingNo)
                        .isNull(ErpSendOutGoods::getProof));
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (sendOutGoodList != null && sendOutGoodList.size() > 0) { // 采购没购买
            // 查询整个订单的采购成本
            // 获取订单发货国家
            AeStoreOrderReceiptAddress address = storeOrderReceiptAddressMapper
                    .selectOne(new LambdaQueryWrapper<AeStoreOrderReceiptAddress>()
                            .eq(AeStoreOrderReceiptAddress::getOrderId, orderId));
            for (ErpSellerChildOrder childOrder : childOrderList) {
                ErpCollectProductSkuPrice bySkuCode = productSkuPriceService.getBySkuCode(childOrder.getSkuCode());

                String absoluteQuoteMap = bySkuCode.getAbsoluteQuoteMap();
                Map<String, Object> map = JSON.parseObject(absoluteQuoteMap);
                // 根据国家查询单价
                Long productCount = childOrder.getProductCount();
                String amountStr = (String) map.get(address.getCountry());
                BigDecimal amount = BigDecimal.ZERO;
                if (StringUtils.isEmpty(amountStr)) {
                    amount = new BigDecimal(bySkuCode.getSkuPrice());
                } else {
                    amount = new BigDecimal(amountStr);
                }
                amount = amount.multiply(new BigDecimal(productCount));
                totalAmount = amount.add(totalAmount);
            }
            Long currentTimeMillis = System.currentTimeMillis();
            R<Object> returnR = iErpSellerStoreWalletService.updateWallet(FlowType.INCOME.getCode(),
                    ExpenseType.ORDERREFUND.getCode(), PayType.XT.getCode(), totalAmount, userId,
                    currentTimeMillis.toString(), "");
            if (returnR.getCode() == 200) {
                statusIntro = "截单成功，已退款";
            } else {
                return returnR;
            }
        } else {
            // 先看订单是否创建出库委托
            String outBound = getOutBound(orderId.toString());
            JSONObject outBoundJsonObject = JSONObject.parseObject(outBound);
            JSONArray outBoundData = outBoundJsonObject.getJSONObject("data").getJSONArray("data");
            if (ObjectUtils.isNotEmpty(outBoundData)) {
                // 不为空,订单已创建出库委托,需要取消出库
                String cancelOutBound = cancelOutBound(orderId);
                JSONObject cancelOutBoundJson = JSONObject.parseObject(cancelOutBound);
                String result = cancelOutBoundJson.getString("result");
                if ("0".equals(result)) { // 取消失败
                    String msg = cancelOutBoundJson.getString("msg");
                    JSONArray errors = cancelOutBoundJson.getJSONArray("errors");
                    String errorMsg = errors.getJSONObject(0).getString("error_msg");
                    return R.fail(msg + " " + errorMsg);
                }
            }
            for (ErpSellerChildOrder childOrder : childOrderList) {
                String skuCode = childOrder.getSkuCode();
                Integer productCount = childOrder.getProductCount().intValue();
                FpxWarehousInfo warehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
                        .eq(FpxWarehousInfo::getSkuCode, skuCode).eq(FpxWarehousInfo::getUserId, userId));
                ErpSendOutGoods sendOutGoods = erpSendOutGoodsMapper.selectOne(new LambdaQueryWrapper<ErpSendOutGoods>()
                        .eq(ErpSendOutGoods::getChildOrderId, childOrder.getChildOrderId())
                        .eq(ErpSendOutGoods::getIsUse, 1));

                if (warehousInfo == null) {
                    FpxWarehousInfo info = new FpxWarehousInfo();
                    info.setSkuCode(skuCode);
                    info.setOnwayStock(productCount);
                    info.setPendingStock(0);
                    info.setAvailableStock(0);
                    info.setUserId(userId);
                    warehousInfoMapper.insert(info);
                } else {
                    warehousInfo.setOnwayStock(productCount + warehousInfo.getOnwayStock());
                    warehousInfoMapper.updateById(warehousInfo);
                }
                // 添加库存记录
                FpxWarehousRecord warehousRecord = new FpxWarehousRecord();
                warehousRecord.setUserId(userId);
                warehousRecord.setRefNo(sendOutGoods.getTrackingNo());
                warehousRecord.setStatus(0);
                warehousRecord.setSkuCode(skuCode);
                warehousRecord.setSkuPlanQty(productCount);
                warehousRecordMapper.insert(warehousRecord);
            }
            statusIntro = "截单成功，商品将仓储";
        }
        // 添加日志
        String storeNameByUserName = empowerService.getStoreNameByUserName(sellerLoginId);
        for (ErpSellerChildOrder childOrder : childOrderList) {
            ErpSellerOrderLogBo orderLogBo = new ErpSellerOrderLogBo();
            orderLogBo.setOrderId(orderId);
            orderLogBo.setChildOrderId(childOrder.getChildOrderId());
            orderLogBo.setStoreName(storeNameByUserName);
            orderLogBo.setStatusIntro(statusIntro);
            orderLogBo.setErpAccount(empowerService.queryUserNameBySellerLoginId(sellerLoginId));
            orderLogService.insertByBo(orderLogBo);
        }

        sellerOrderService.setInnerStatus(orderId, "502");
        return R.ok();
    }*/

    /**
     * 截单后仓储
     */
    /*@PostMapping("/cutOrderStorage")
    @Transactional
    @RepeatSubmit
    public R<Object> cutOrderStorage(@RequestBody List<OrderParam> orderParamList) {
        Long orderId = 0L;
        boolean isOutBound = true;
        for (OrderParam orderParam : orderParamList) {
            String trackingNo = orderParam.getTrackingNo();
            Long arrivalTime = orderParam.getArrivalTime();
            String childOrderId = orderParam.getChildOrderId();
            orderId = orderParam.getOrderId();
            ErpSellerChildOrder childOrder = sellerChildOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getChildOrderId, childOrderId));
            Integer productCount = childOrder.getProductCount().intValue();
            String skuCode = childOrder.getSkuCode();
            // 没填国内运单号和预计到货时间不入库
            if (ObjectUtils.isEmpty(trackingNo) || ObjectUtils.isEmpty(arrivalTime)) {
                continue;
            }
            // 找采购成本
            String proof = null;
            String cost = null;
            ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
                    .eq(ErpSellerChildOrderExtend::getChildOrderId, childOrderId));
            if (childOrderExtend != null) {
                proof = childOrderExtend.getProof();
                Double purchasePrice = childOrderExtend.getPurchasePrice();
                if (purchasePrice != null) {
                    cost = purchasePrice.toString();
                }
            }
            // 先看订单是否创建入库委托
            String inboundInfo = getInBound(childOrderId);
            JSONObject inBoundJsonObject = JSONObject.parseObject(inboundInfo);
            JSONArray inBoundData = inBoundJsonObject.getJSONObject("data").getJSONArray("data");
            // 已经创建了入库
            if (ObjectUtils.isNotEmpty(inBoundData)) {
                // 是否创建出库
                if (isOutBound) {
                    String outBound = getOutBound(orderId.toString());
                    JSONObject outBoundJsonObject = JSONObject.parseObject(outBound);
                    JSONArray outBoundData = outBoundJsonObject.getJSONObject("data").getJSONArray("data");
                    if (ObjectUtils.isNotEmpty(outBoundData)) {
                        String cancelOutBound = cancelOutBound(orderId);
                        JSONObject cancelOutBoundJson = JSONObject.parseObject(cancelOutBound);
                        String result = cancelOutBoundJson.getString("result");
                        if ("0".equals(result)) { // 取消失败
                            String msg = cancelOutBoundJson.getString("msg");
                            JSONArray errors = cancelOutBoundJson.getJSONArray("errors");
                            String errorMsg = errors.getJSONObject(0).getString("error_msg");
                            return R.fail(msg + " " + errorMsg);
                        }
                        isOutBound = false;
                    }

                }
                String consignNo = inBoundData.getJSONObject(0).getString("consignment_no");
                // 已入库,加记录
                updateOnwayStock(trackingNo, productCount, skuCode, 1L, consignNo, proof, cost);
            } else {
                // 没创建需要创建入库
                R<String> inBound = createInBound(childOrderId, trackingNo, arrivalTime, productCount, skuCode);
                if (inBound.getCode() != 200) { // 入库失败
                    R<Object> objectR = new R<>();
                    objectR.setMsg(inBound.getMsg());
                    objectR.setCode(inBound.getCode());
                    objectR.setData(inBound.getData());
                    return objectR;
                } else {
                    String msg = inBound.getMsg();
                    JSONObject jsonObject = JSONObject.parseObject(msg);
                    String consignNo = jsonObject.getJSONObject("data").getString("consignment_no");
                    updateOnwayStock(trackingNo, productCount, skuCode, 1L, consignNo, proof, cost);
                }
            }

        }
        // 循环完成后改为截单成功,退款,添加订单日志
        ErpSellerStoreWalletLog walletLog = walletLogService.selectMoney(orderId.toString());
        BigDecimal totalAmount = walletLog.getMoney();
        Long sellerId = walletLog.getSellerId();
        iErpSellerStoreWalletService.updateWallet(FlowType.INCOME.getCode(), ExpenseType.PURCHASEREFUND.getCode(), PayType.XT.getCode(), totalAmount, sellerId, orderId.toString(), "");

        orderLogService.createOrderLog(orderId, null, OrderLogType.CutOrderSuccess,
                null, OrderProcessFlag.CutOff.getInfo(), "502");

        sellerOrderService.setInnerStatus(orderId, "502", OrderProcessFlag.CutOff.getInfo());

        return R.ok();
    }*/

//    private void updateOnwayStock(String trackingNo, Integer productCount, String skuCode, Long userId,
//                                  String consignNo, String proof, String cost) {
//        // 根据skuCode查询sku信息
//        ErpCollectProductSku skuInfo = collectProductSkuMapper.selectOne(
//                new LambdaQueryWrapper<ErpCollectProductSku>()
//                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
//                        .eq(ErpCollectProductSku::getDelFlag, "0")
//        );
//        Long collectProductId = skuInfo.getCollectProductId();
//        ErpCollectProduct collectProduct = collectProductMapper.selectById(collectProductId);
//        FpxWarehousInfo warehousInfo = warehousInfoMapper.selectOne(new LambdaQueryWrapper<FpxWarehousInfo>()
//                .eq(FpxWarehousInfo::getSkuCode, skuCode).eq(FpxWarehousInfo::getUserId, 1L)); // 公司仓储信息
//        if (warehousInfo == null) {
//            FpxWarehousInfo info = new FpxWarehousInfo();
//            info.setSkuCode(skuCode);
//            info.setOnwayStock(productCount);
//            info.setPendingStock(0);
//            info.setAvailableStock(0);
//            info.setUserId(1L);
//            info.setSkuImage(skuInfo.getSkuImage());
//            info.setSkuName(collectProduct.getSubject());
//            warehousInfoMapper.insert(info);
//        } else {
//            warehousInfo.setOnwayStock(productCount + warehousInfo.getOnwayStock());
//            warehousInfoMapper.updateById(warehousInfo);
//        }
//        // 添加库存记录
//        FpxWarehousRecord warehousRecord = new FpxWarehousRecord();
//        warehousRecord.setUserId(1L);
//        warehousRecord.setRefNo(trackingNo);
//        warehousRecord.setStatus(0);
//        warehousRecord.setSkuCode(skuCode);
//        warehousRecord.setSkuPlanQty(productCount);
//        warehousRecord.setConsignmentNo(consignNo);
//        warehousRecord.setProof(proof);
//        warehousRecord.setPurchasePrice(cost);
//        warehousRecordMapper.insert(warehousRecord);
//    }

    /**
     * 截单失败
     */
    @PostMapping("/cutOrderFail")
    public R<String> cutOrderFail(@RequestBody OrderParam orderParam) {
        Long orderId = orderParam.getOrderId();
        String remark = orderParam.getRemark();
        // 截单失败,根据日志使订单回到原来的状态继续流程
        ErpSellerOrderLog statusIntro = remoteErpOrderLogService.getStatusIntro(orderId);
        String currentOrderProcess = statusIntro.getPreviousStatus();
        String previousOrderProcess = statusIntro.getPreviousOrderProcess();
        remoteErpOrderService.setInnerStatus(orderId, currentOrderProcess, previousOrderProcess);
        remoteErpOrderLogService.createOrderLog(orderId, null, OrderLogType.CutOrderFail,
                remark, currentOrderProcess, statusIntro.getCurrentStatus());

        return R.ok();
    }



    /**
     * 4px库存查询
     */
    @PostMapping("/getWareHouseStock")
    public TableDataInfo<WareHouseStock> getWareHouseStock(@RequestBody WareHouseStock stock) {
        AffterentParam publicParam = new AffterentParam();
        publicParam.setVersion("1.0.0");
        publicParam.setMethod("fu.wms.inventory.get");
        publicParam.setAppKey(FPS_APP_KEY);
        publicParam.setAppSecret(FPS_APP_SECRET);
        publicParam.setFormat("json");
        publicParam.setLanguage("CN");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("lstsku", stock.getLstsku());
        paramMap.put("warehouse_code", "CNDGMB");
        paramMap.put("page_no", stock.getPageNo());
        paramMap.put("page_size", stock.getPageSize());
        String post = ApiHttpClientUtils.apiJsongPost(publicParam, paramMap, AmbientEnum.FORMAT_ADDRESS);
        JSONObject jsonObject = JSONObject.parseObject(post);
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("data");
        String s = jsonArray.toJSONString();
        List<WareHouseStock> wareHouseStockList = JSONObject.parseArray(s, WareHouseStock.class);
        return TableDataInfo.build(wareHouseStockList);
    }

    /**
     * 取消入库委托
     */
    @GetMapping("/cancelInBound")
    public R<String> cancelInBound(String childOrderId) {
        AffterentParam param = new AffterentParam();
        param.setMethod("fu.wms.inbound.cancel");
        param.setAppKey(FPS_APP_KEY);
        param.setAppSecret(FPS_APP_SECRET);
        param.setVersion("1.0.0");
        param.setFormat("json");
        param.setLanguage("CN");
        Map<String, Object> map = new HashMap<>();
        map.put("ref_no", childOrderId);
        String s = ApiHttpClientUtils.apiJsongPost(param, map, AmbientEnum.FORMAT_ADDRESS);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String result = jsonObject.getString("result");
        if ("0".equals(result)) {
            return R.fail(jsonObject.getString("msg"));
        }
        return R.ok();
    }

    /**
     * 获取物流产品代码
     */
    @GetMapping("/getLpCode")
    public R<Object> getLpCode() {
//        List<ErpLogisticsProductInfoVo> codeInfo = logisticsProductInfoService
//                .queryList(new ErpLogisticsProductInfoBo());
//        List<Map<String, String>> list = new ArrayList<>();
////        codeInfo.forEach(code -> {
////            Map<String, String> paramMap = new HashMap<>();
////            paramMap.put("label",code.getLogisticsProductName());
////            paramMap.put("value",code.getLogisticsProductCode());
////            list.add(paramMap);
////        });
//        Map<String, Object> paramMap = new HashMap<>();
//        return R.ok(codeInfo);
        return R.ok();
    }

}
